package com.so.web.controller.system;

import com.so.common.annotation.Log;
import com.so.common.config.ProjectConfig;
import com.so.common.core.controller.BaseController;
import com.so.common.core.domain.R;
import com.so.common.core.domain.entity.SysUser;
import com.so.common.core.domain.model.LoginUser;
import com.so.common.enums.BusinessType;
import com.so.common.exception.file.FileException;
import com.so.common.utils.SecurityUtils;
import com.so.common.utils.StringUtils;
import com.so.common.utils.file.FileUploadUtils;
import com.so.common.utils.file.MimeTypeUtils;
import com.so.framework.web.service.TokenService;
import com.so.system.service.ISysUserService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 个人信息 业务处理
 *
 * @author system
 */
@RestController
@RequestMapping("/system/user/profile")
public class SysProfileController extends BaseController {

    @Resource
    private ISysUserService userService;

    @Resource
    private TokenService tokenService;

    /**
     * 个人信息
     */
    @GetMapping
    public R<Map<String,Object>> profile() {
        LoginUser loginUser = getLoginUser();
        Map<String,Object> result = new HashMap<>(2);
        result.put("roleGroup", userService.selectUserRoleGroup(loginUser.getUsername()));
        result.put("postGroup", userService.selectUserPostGroup(loginUser.getUsername()));
        return R.ok(result);
    }

    /**
     * 修改用户
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public R<Void> updateProfile(@RequestBody SysUser user) {
        LoginUser loginUser = getLoginUser();
        SysUser currentUser = loginUser.getUser();
        currentUser.setNickName(user.getNickName());
        currentUser.setEmail(user.getEmail());
        currentUser.setPhoneNumber(user.getPhoneNumber());
        currentUser.setSex(user.getSex());
        if (StringUtils.isNotEmpty(user.getPhoneNumber()) && !userService.checkPhoneUnique(currentUser)) {
            return R.fail("修改用户'" + loginUser.getUsername() + "'失败，手机号码已存在");
        }
        if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(currentUser)) {
            return R.fail("修改用户'" + loginUser.getUsername() + "'失败，邮箱账号已存在");
        }
        if (userService.updateUserProfile(currentUser) > 0) {
            // 更新缓存用户信息
            tokenService.setLoginUser(loginUser);
            return R.ok();
        }
        return R.fail("修改个人信息异常，请联系管理员");
    }

    /**
     * 重置密码
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping("/updatePwd")
    public R<Void> updatePwd(String oldPassword, String newPassword) {
        LoginUser loginUser = getLoginUser();
        String userName = loginUser.getUsername();
        String password = loginUser.getPassword();
        if (!SecurityUtils.matchesPassword(oldPassword, password)) {
            return R.fail("修改密码失败，旧密码错误");
        }
        if (SecurityUtils.matchesPassword(newPassword, password)) {
            return R.fail("新密码不能与旧密码相同");
        }
        newPassword = SecurityUtils.encryptPassword(newPassword);
        if (userService.resetUserPwd(userName, newPassword) > 0) {
            // 更新缓存用户密码
            loginUser.getUser().setPassword(newPassword);
            tokenService.setLoginUser(loginUser);
            return R.ok();
        }
        return R.fail("修改密码异常，请联系管理员");
    }

    /**
     * 头像上传
     */
    @Log(title = "用户头像", businessType = BusinessType.UPDATE)
    @PostMapping("/avatar")
    public R<Map<String,String>> avatar(@RequestParam("avatarfile") MultipartFile file) throws Exception {

        if(file.isEmpty()){
            throw new FileException("上传文件不能为空");
        }

        LoginUser loginUser = getLoginUser();
        String avatar = FileUploadUtils.upload(ProjectConfig.getAvatarPath(), file, MimeTypeUtils.IMAGE_EXTENSION);
        userService.updateUserAvatar(loginUser.getUsername(), avatar);
        Map<String,String> result = new HashMap<>(1);
        result.put("imgUrl", avatar);
        // 更新缓存用户头像
        loginUser.getUser().setAvatar(avatar);
        tokenService.setLoginUser(loginUser);
        return R.ok(result);

    }

}
